package com.dq.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/***
 * 文件下载保存工具类
 */

public class FileUtil {

    private static final String saveDir = File.separator + "saveDir" + File.separator;

    /**
     * 1.保存
     * 2.增加一层目录, 以免文件过多
     */
    public static final File save(MultipartFile file) throws IOException {
        if (null == file || file.isEmpty()) {
            return null;
        }
        String path = String.format("%s%s%s", TimeUtil.getNowString(TimeUtil.YYYY_MM_DD), File.separator, file.getOriginalFilename());
//        String os = System.getenv("os");
        String os = "windows";
        if (null != os && os.toLowerCase().contains("windows")) {
            File saved = new File(new File("").getAbsolutePath() + saveDir + path);
            saved.getParentFile().mkdirs();
            file.transferTo(saved);
            return saved;
        } else {
            File saved = new File(saveDir + path);
            saved.getParentFile().mkdirs();
            file.transferTo(saved); // 使用相对路径时保存失败
            return saved;
        }
    }

    /**
     * 1.随机重命名保存, 后缀名不变
     * 2.增加一层目录, 以免文件过多
     */
    public static final String renameAndSave(MultipartFile file) throws IOException {
        if (null == file || file.isEmpty()) {
            return null;
        }
        String path = String.format("%s%s%s.%s", TimeUtil.getNowString(TimeUtil.YYYY_MM_DD), File.separator,
                RandomStringUtils.randomAlphanumeric(16), FileUtil.getExtName(file));
        File saved = new File(saveDir + path);
        saved.getParentFile().mkdirs();
        file.transferTo(saved);
        return path;
    }

    public static final File renameAndSaveAndGetFile(MultipartFile file) throws IOException {
        return getFile(renameAndSave(file));
    }

    public static final File getFile(String path) {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (path.startsWith(saveDir)) {
            return new File(path);
        }
        return new File(saveDir + path);
    }

    public static final String getPath(String path) {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (path.startsWith(saveDir)) {
            return path;
        }
        return saveDir + path;
    }

    public static final String getExtName(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String[] names = filename.split("\\.");
        return names[names.length - 1];
    }

    public static final String getExtName(String filename) {
        String[] names = filename.split("\\.");
        return names[names.length - 1];
    }
}
